#include "rs_vsync_client_ohos.h"

#include <chrono>
#include <cstring>
#include <sys/prctl.h>

#include "native_vsync.h"
#include "platform/common/rs_log.h"

namespace Keels {
namespace Rosen {
std::unique_ptr<RSVsyncClient> RSVsyncClient::Create() {
    return std::make_unique<RSVsyncClientOhos>();
}

RSVsyncClientOhos::RSVsyncClientOhos()
{
    constexpr const char* name = "keels";
    ohVSync_ = OH_NativeVSync_Create(name, std::strlen(name));
    OH_NativeVSync_RequestFrame(ohVSync_, OnVsync, this);
    running_ = true;
}

RSVsyncClientOhos::~RSVsyncClientOhos()
{
    if (ohVSync_) {
        OH_NativeVSync_Destroy(ohVSync_);
    }
    running_ = false;
}

void RSVsyncClientOhos::OnVsync(long long frameTimeNanos, void* data)
{
    auto client = static_cast<RSVsyncClientOhos*>(data);
    if (client && client->running_ && client->vsyncCallback_) {
        client->having_ = false;
        int64_t now = static_cast<int64_t>(frameTimeNanos);
        std::unique_lock lock(client->mutex_);
        client->vsyncCallback_(now, 0);
    }
}

void RSVsyncClientOhos::RequestNextVsync()
{
    if (!running_) {
        return;
    }
    OH_NativeVSync_RequestFrame(ohVSync_, OnVsync, this);
}

void RSVsyncClientOhos::SetVsyncCallback(VsyncCallback callback)
{
    std::unique_lock lock(mutex_);
    vsyncCallback_ = callback;
}
} // namespace Rosen
} // namespace Keels